<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <table>
        <tr>
            <th>
                <input id="check-all" type="checkbox" name="" id="">
            </th>
            <th>表头第2列</th>
            <th>表头第3列</th>
        </tr>
        <tr>
            <td>
                <input class="check-one" type="checkbox" name="" id="">
            </td>
            <td>内容</td>
            <td>内容</td>
        </tr>
        <tr>
            <td>
                <input class="check-one" type="checkbox" name="" id="">
            </td>
            <td>内容</td>
            <td>内容</td>
        </tr>
        <tr>
            <td>
                <input class="check-one" type="checkbox" name="" id="">
            </td>
            <td>内容</td>
            <td>内容</td>
        </tr>
        <tr>
            <td>
                <input class="check-one" type="checkbox" name="" id="">
            </td>
            <td>内容</td>
            <td>内容</td>
        </tr>
    </table>

    <script>

        // const arr = new Array(4).fill(true);

        // 全选按钮
        const checkAll = document.querySelector('#check-all');
        // 下面的所有复选框
        const checkboxes = document.querySelectorAll('.check-one');

        // 状态
        const state = {
            all: false,
            checkboxes: [
                false,
                false,
                false,
                false,
            ],
        };

        // 渲染函数
        function render () {
            checkAll.checked = state.all;
            for (let i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = state.checkboxes[i];
            }
        }

        checkAll.addEventListener('click', function () {
            // 1. 改state
            state.all = checkAll.checked;
            state.checkboxes = new Array(4).fill(checkAll.checked);
            // 2. 渲染
            render();
        });

        for (let i = 0; i < checkboxes.length; i++) {
            checkboxes[i].addEventListener('click', function () {
                // 1. 改state
                state.checkboxes[i] = this.checked;
                // let flag = true;
                // for (const checked of state.checkboxes) {
                //     if (!checked) {
                //         flag = false;
                //         break;
                //     }
                // }
                // state.all = flag;
                state.all = state.checkboxes.every(function (item) {
                    return !!item;
                });
                // 2. 渲染
                render();
            });
        }


    </script>

</body>
</html>